require(['./config'], () => {
    require(['template','url','header','jquery','fly'], (template,url,header,jquery,fly) => {
        class Buys {
            constructor () {
                this.addfooter()
                this.addBuys().then(()=>{
                    this.addcard();
                })
            }
            addfooter(){
                $('footer').load('../html/footer.html')
            }
            addBuys(){
                //提取id
                const id = Number(window.location.search.slice(4))
                return new Promise( resolve => {
                    //请求详情
                    $.get(url.baseUrl + '/buys',{id},resp =>{
                        if(resp.code === 200){
                            const { buys } = resp.body
                            //手动加id 真实接口不需要
                            this.buys = { ...buys , id }
                            this.renderBuys()
                            return resolve();
                        }
                    })
                })
            }
            renderBuys(){
                $('.content').html(template('cont',{...this.buys}))
                this.enlarge()
                this.card()
                console.log(this.buys);
            }
            addcard(){
                $('.addCard').on('click',(e)=>{
                    //添加点击事件，把数据存入localStorage
                    this.fly(e);
                    //先获取数据
                    let card = localStorage.getItem('card')
                    //如果有数据提取出来再存
                    if(card){
                        //取出数组
                        card = JSON.parse(card)
                        //如果商品存在，count++,不存在才push
                        const isExist = card.some(shop => shop.id === this.buys.id)
                        if(isExist){
                            card = card.map(shop => {
                               if(shop.id === this.buys.id) shop.count++
                                return shop
                            })
                        }else{
                            //向数组push当前 数据 ,并添加count=1，check默认为true-选中状态
                            card.push({...this.buys,count:1,check:true})
                        }
                        
                        //把整个数组存储到localStorage
                        localStorage.setItem('card',JSON.stringify(card))
                    }else{
                        //如果没有数据直接添加,并添加count=1,check默认为true-选中状态
                        localStorage.setItem('card',JSON.stringify([{...this.buys,count:1,check:true}]))
                    }
                })
            }
            fly(e){
                let img = $('.show img').attr('src')
                $(`<img src="${img}" style="width:26px; height:26px; border-radius:50%;"></img>`).fly({
                    start:{
                      left: e.clientX,  //开始位置（必填）#fly元素会被设置成position: fixed
                      top:  e.clientY,  //开始位置（必填）
                    },
                    end:{
                      left: $('.gocard').offset().left - $(window).scrollLeft(), //结束位置（必填）
                      top: $('.gocard').offset().top - $(window).scrollTop(),  //结束位置（必填）
                    },
                    speed: 1, //越大越快，默认1.2
                    vertex_Rtop:100, //运动轨迹最高点top值，默认20
                    onEnd: function(){
                        this.destroy(); //移除dom
                        header.cardCount()
                    } //结束回调
                });
            }
            enlarge(){
            let shop = $('.shop'),
                show = $('.show'),
                mask = $('.mask'),
                smallImg = $('.smallImg'),
                lis = $('li'),
                enlarge = $('.enlarge')

                //获取.active 元素里img的src
                var cover =  $('.active').children().attr('src')
                //赋值给放大镜
                enlarge.css('background',`url('${cover}')`)
                enlarge.css('background-repeat','no-repeat')
                show.hover(
                   function () {
                        mask.show();
                        enlarge.show();
    
                        $(this).on('mousemove',function(e){
                            let xx = e.originalEvent.x ||e.originalEvent.layerX || 0;      
                            let yy = e.originalEvent.y ||e.originalEvent.layerY || 0;   
                             
                            var x =  xx -  show.offset().left -mask.width()/2;
                            var y =  yy -   show.offset().top - mask.height()/2;
                           
                            
                            if(x<=0){ x=0; }
                            if(y<=0){ y=0; }
                            if( x >= show.width() - mask.width()){
                                x  =  show.width() - mask.width();
                             }
                            if( y >= show.height()  - mask.height()){
                                y =  show.height()  - mask.height();
                            }
                            mask.css('left',`${x}px`);
                            mask.css('top',`${y}px`);
    
                            let f1 = x / show.width() *  800;
                            let f2 = y / show.height() *  800;
                            enlarge.css('backgroundPosition',`${-f1}px  ${-f2}px`)
    
                            let l1 = x + mask.width()+10
                            let l2 = y  + mask.height()/2;
                            enlarge.css('left',`${l1}px`)
                            enlarge.css('top',`${l2}px`)
                        })
                    },
                    function () {
                        mask.hide();
                        enlarge.hide();
                   })
    
                    lis.on('click',function(){
                    $(this).addClass('active').siblings().removeClass('active')
                    var tu =  $(this).children().attr('src')
                   
                    $('.show img').attr('src',tu)
                    var pian =  $('.show img').attr('src')
                    enlarge.css('background',`url('${pian}')`)
                    enlarge.css('background-repeat','no-repeat')
                  })
            }
            card(){
                //默认给第一个元素添加.foods
                $('.food div').eq(0).addClass('foods')
                $('.food div').on('click',function(){
                    //获取所有div,给当前元素添加点击事件
                    $(this).addClass('foods').siblings().removeClass('foods')
                    //关联相应选项内容
                    $('.con').eq($(this).index()).addClass('xuan').siblings().removeClass('xuan')

                })
            }
        }
        new Buys()
    })
})